package com.tedu.web;

import com.tedu.dao.UserMapper;
import com.tedu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户的控制器
 */
@Controller
public class UserController {
    @Autowired
    UserMapper mapper;


    /**
     * 用户登录
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, HttpSession session,Model model){
        //获取用户登录时，传递用户名+密码
        System.out.println(user);
        List<User> userByUser = mapper.getUserByUser(user);
        System.out.println(userByUser);
        if(userByUser.size()>0){
            session.setAttribute("user",userByUser.get(0));
            return "index";//登录成功
        }
        model.addAttribute("info","你的用户名密码错误，请重新登录");
        return "login";
    }

    /**
     * 显示注册页面
     */
    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    /**
     * 用户注册
     * @return  登录
     */
    @RequestMapping("/userregister")
    public String userregister(User user){
        System.out.println(user);
        //调用mapper  注册
        int i = mapper.insertUser(user);
        if(i>0){
            //注册成功
            return "login";
        }else{
            return "register";
        }


    }

    /**
     * 判断是否名是否重复
     * @param name
     * @return
     */
    @RequestMapping("/userName")
    @ResponseBody //以文本方式返回
    public String userName(String name){
        System.out.println("你正在请求用户名是否存在"+name);
        List<User> userByName = mapper.getUserByName(name);

        if(userByName!=null&&userByName.size()>0){
            //该用户已经存在
            return "exit";
        }else{
            return "noexit";
        }



    }


}
